﻿using huangyufan.OpenDataService.Context;
using huangyufan.OpenDataService.Model;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace huangyufan.OpenDataService.Middleware
{
    public class DbWebApiMiddleware
    {
        private readonly RequestDelegate _next;
        private IConfiguration Configuration;

        public DbWebApiMiddleware(RequestDelegate next, IConfiguration configuration)
        {
            _next = next;
            Configuration= configuration;
        }
        public async Task InvokeAsync(HttpContext context)
        {
            
            string tableName= $"ODV_{context.Request.Path.Value.Remove(0,1).ToUpper()}";
            string requestData = string.Empty;
            using (var streamReader = new StreamReader(context.Request.Body, Encoding.UTF8))
            {

                requestData = streamReader.ReadToEndAsync().Result;
            }

            string sqlStr = $"select * from {tableName} where 1=1 ";
            JObject jo = JObject.Parse(requestData);
            foreach (var item in jo)
            {
                if (item.Key== "TimeSlot")
                {
                    continue;
                }
                sqlStr += $"and {item.Key}='{item.Value}' ";
            }

            if (jo.ContainsKey("TimeSlot"))
            {
                string strTimeSlot = jo["TimeSlot"].ToString();

                bool TimeSlotIsJson = false;
                try
                {
                    JArray.Parse(strTimeSlot);
                    TimeSlotIsJson = true;

                }
                catch (System.Exception)
                {
                    TimeSlotIsJson = false;

                }

                try
                {
                    if (TimeSlotIsJson)
                    {
                        List<TimeSlot> timeSlots = Newtonsoft.Json.JsonConvert.DeserializeObject<List<TimeSlot>>(strTimeSlot);

                        foreach (var timeSlot in timeSlots)
                        {
                            sqlStr += $"and {timeSlot.ColumnName} between '{timeSlot.BeginTime.ToString("yyyy-MM-dd HH:mm:ss")}' and '{timeSlot.EndTime.ToString("yyyy-MM-dd HH:mm:ss")}' ";
                        }
                    }
                    else
                    {
                        sqlStr += $"and TimeSlot='{jo["TimeSlot"].ToString()}' ";
                    }
                }
                catch (System.Exception)
                {
                    context.Response.StatusCode = 415;
                }
            }
            
            

            var dataTable=SqlHelper.ExcuteDataTable(Configuration.GetConnectionString("DefaultConnection"), sqlStr);

            string result = Newtonsoft.Json.JsonConvert.SerializeObject(dataTable);
            await context.Response.WriteAsync(result);

            await _next(context);
        }
    }

    public static class DbWebApiMiddlewareExtensions
    {
        public static IApplicationBuilder UseDbWebApiMiddleware(
            this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<DbWebApiMiddleware>();
        }
    }
}
